/******************************************************************************
 * @File name   :      UserApprovalRuleServiceImpl.java
 *
 * @Author      :      chengli
 *
 * @Date        :      2011-7-19
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-7-19 上午09:44:55        chengli     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.framework.dm.approval.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.ge.dealer.dao.IDealerDao;
import com.cap.bts.commonfunc.ge.dealer.domain.DealerInfo;
import com.cap.bts.framework.approvalrule.constants.ApprovalResult;
import com.cap.bts.framework.approvalrule.constants.ApprovalStatus;
import com.cap.bts.framework.approvalrule.dao.IApplicationApprovalDao;
import com.cap.bts.framework.approvalrule.dao.IApplicationRuleStepDao;
import com.cap.bts.framework.approvalrule.dao.IApprovalRuleDao;
import com.cap.bts.framework.approvalrule.domain.ApplicationApproval;
import com.cap.bts.framework.approvalrule.domain.ApplicationRuleStep;
import com.cap.bts.framework.approvalrule.domain.ApprovalRule;
import com.cap.bts.framework.common.dto.ApprovalRuleDto;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.common.util.CodeTextUtils;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.dm.approval.dao.IDealerUsrGrpApprovalDao;
import com.cap.bts.framework.dm.approval.domain.UserGroupApplication;
import com.cap.bts.framework.dm.approval.dto.ApprovalResultDto;
import com.cap.bts.framework.dm.approval.service.IUserApprovalRuleService;
import com.cap.bts.framework.usermgnt.constant.OrganizationType;
import com.cap.bts.framework.usermgnt.dao.IUserDao;
import com.cap.bts.framework.usermgnt.dao.IUserGroupDao;
import com.cap.bts.framework.usermgnt.domain.EmployeeInfo;
import com.cap.bts.framework.usermgnt.domain.Organization;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.service.IOrganizationMgntService;

/**
 * 人员岗位审批节点查询服务类 主要功能如下： 
 * 1.通过webService服务供dms端查询人员岗位审批节点信息；
 * 2.根据dms
 * 登陆用户的岗位查询已审批操作历史记录信息；
 * 
 */
@Transactional(rollbackFor = AppException.class)
@Service("userApprovalRuleServiceImpl") 
public class UserApprovalRuleServiceImpl extends BaseServiceImpl implements
		IUserApprovalRuleService {
	@Resource(name = "organizationMgntServiceImpl")
    private IOrganizationMgntService orgMgntService;
	@Resource(name = "dealerUsrGrpApprovalDao")
    private IDealerUsrGrpApprovalDao dealerUsrGrpApprovalDao;
	@Resource(name = "dealerDao")
    private IDealerDao dealerDao;
	@Resource(name = "userGroupDao")
    private IUserGroupDao userGroupDao;
	@Resource(name = "applicationApprovalDao")
    private IApplicationApprovalDao applicationApprovalDao;
	@Resource(name = "approvalRuleDao")
	private IApprovalRuleDao approvalRuleDao;
	@Resource(name="userDao")
	private IUserDao userDao;
	@Resource(name="applicationRuleStepDao")
	private IApplicationRuleStepDao applicationRuleStepDao;
	

	@Override
	public List<ApprovalRuleDto> getHisApprovalByAppIdAndType(long appId,int applicationType)throws AppException{
		  List<ApplicationApproval> hisAppApproveList=applicationApprovalDao.getApprovalByAppIdOrderById(appId, applicationType);
		  if(hisAppApproveList!=null && hisAppApproveList.size()>0){
	        	List<ApprovalRuleDto> hisApproveList=new ArrayList<ApprovalRuleDto>();
	        	ApprovalRuleDto approveRuleDto=null;
	        	for(ApplicationApproval temp:hisAppApproveList){
	        		approveRuleDto=new ApprovalRuleDto();
	        		if(Utils.notEmpty(temp.getStepCode())){
	        			ApprovalRule approvalRule =approvalRuleDao.getRuleByStepCode(temp.getStepCode());
	        			UserGroup userGroup = userGroupDao.getUserGroupByCode(approvalRule.getUserGroupCode());
	        			if(userGroup!=null){
	        				approveRuleDto.setUserGroupName(userGroup.getUserGroupName());
	                	 }
	        		}
	        		if(temp.getApproverUserId()>0){
	        			User user=userDao.findById(temp.getApproverUserId());
	        			if(user!=null){
	        				approveRuleDto.setApproveUserName(user.getName());
	        			}
	        		}
	        		approveRuleDto.setApproveResult(new Long(temp.getApproverResult()));
	        		approveRuleDto.setApproveDate(temp.getApproverTime());
	        		approveRuleDto.setApproveMemo(temp.getApproverRemark());
	        		hisApproveList.add(approveRuleDto);
	        	}
	        	return hisApproveList;
	        }
		  return null;
	}
	
	@Override
	public List<ApprovalRuleDto> getCurApprovalByAppIdAndType(long appId,int applicationType)throws AppException{
		List<ApplicationRuleStep> curRuleList=applicationRuleStepDao.getCurrentRules(appId,applicationType);
		if(curRuleList!=null && curRuleList.size()>0){
			ApprovalRuleDto approveRuleDto=null;
			List<ApprovalRuleDto> curApproveList=new ArrayList<ApprovalRuleDto>();
			for(ApplicationRuleStep temp:curRuleList){
        		approveRuleDto=new ApprovalRuleDto();
        		if(Utils.notEmpty(temp.getRuleStep())){
        			ApprovalRule approvalRule =approvalRuleDao.getRuleByStepCode(temp.getRuleStep());
        			UserGroup userGroup = userGroupDao.getUserGroupByCode(approvalRule.getUserGroupCode());
        			if(userGroup!=null){
        				approveRuleDto.setUserGroupName(userGroup.getUserGroupName());
                	 }else{
                		 continue;
                	 }
        		}
        		curApproveList.add(approveRuleDto);
        	}
			return curApproveList;
		}
		return null;
	}
	
	private ApprovalResultDto setValue(UserGroupApplication usrGrpApp)
			throws AppException {
		ApprovalResultDto appResultDto = new ApprovalResultDto();
		EmployeeInfo empInfo = usrGrpApp.getEmployeeInfo();
		appResultDto.setApplicationId(usrGrpApp.getId());
	    appResultDto.setEmployeeId(empInfo.getId());
	    appResultDto.setBrandId(usrGrpApp.getBrandId());
		Map<Integer, String> macAndRfsName = getMacAndRfsNameByDealerOrgId(usrGrpApp.getDealerOrgId());
		appResultDto.setMacName(macAndRfsName.get(OrganizationType.MAC));
		appResultDto.setRfsName(macAndRfsName.get(OrganizationType.RFS));
		DealerInfo dealerInfo = dealerDao.findById(empInfo.getDealerId());
		if (dealerInfo != null) {
			appResultDto.setDealerAbbreName(dealerInfo.getDealerAbbreName());
		}
		appResultDto.setUserCode(empInfo.getEmployeeCode());
		appResultDto.setUserName(empInfo.getEmployeeName());
		appResultDto.setMobilePhone(empInfo.getMobilePhone());
		appResultDto.setUserGroupCode(usrGrpApp.getUsrgrpCode());
		if(Utils.notEmpty(usrGrpApp.getUsrgrpCode())){
			UserGroup srcUserGroup = userGroupDao.getUserGroupByCode(usrGrpApp
					.getUsrgrpCode());
			if (srcUserGroup != null) {
				appResultDto.setUserGroupName(srcUserGroup.getUserGroupName());
			}
		}
		if(empInfo.getEmploymentStatusId()!=null){
			 appResultDto.setEmploymentStatus(CodeTextUtils.getText("Employee.WorkStatus", empInfo.getEmploymentStatusId()));
		}
		appResultDto.setApproveTime(usrGrpApp.getCreateDate());
		if(ApprovalStatus.IN_APPROVAL==usrGrpApp.getResult() || ApprovalStatus.PASS_APPROVAL==usrGrpApp.getResult()){
			appResultDto.setApproveResult(ApprovalResult.APPROVAL_AGREE);
		}else if(ApprovalStatus.DO_NOT_APPROVAL==usrGrpApp.getResult()){
			appResultDto.setApproveResult(ApprovalResult.APPROVAL_DISAGREE);
		}
		return appResultDto;
	}
	
	private Map<Integer, String> getMacAndRfsNameByDealerOrgId(long dealerOrgId)
			throws AppException {
		StringBuilder macName = new StringBuilder();
		String rfsOrgCode = null;
		List<Organization> macOrRpcOrgList = orgMgntService
				.getSGMOrgsByDealerOrgId(dealerOrgId);
		Organization macOrg;
		Map<Integer, String> macAndRfsName = new HashMap<Integer, String>();
		if (macOrRpcOrgList != null && macOrRpcOrgList.size() > 0) {
			for (int i = 0, len = macOrRpcOrgList.size(); i < len; i++) {
				macOrg = macOrRpcOrgList.get(i);
				if (macOrg.getOrgType() == OrganizationType.MAC) { // filter rpc
																	// org
					macName.append(macOrg.getOrgName()).append(",");
					rfsOrgCode = macOrg.getParentOrgCode();
				}
			}
			int macNameLen = macName.length();
			macName.delete(macNameLen - 1, macNameLen);
			macAndRfsName.put(OrganizationType.MAC, macName.toString());
		}
		Organization rfsOrgInfo = orgMgntService
				.getOrganizationByOrgCode(rfsOrgCode);
		if (rfsOrgInfo != null) {
			macAndRfsName.put(OrganizationType.RFS, rfsOrgInfo.getOrgName());
		}
		return macAndRfsName;
	}
	  
	  
}
